
    (function($,window){
        window.CommonPageScript = {};
        // 系统公用变量
        CommonPageScript.SysVariable = {
            rootURL:'content/',
            curUser:''
        };

        CommonPageScript.detailSearchCode = '';
        CommonPageScript.detailSearchData = '';
        // 经销商查询请求地址
        CommonPageScript.searchDealerUrl = '';

        // 页面默认执行方法
        CommonPageScript.createDialog = function(dialogOpts, params){
            var dialogOptions = {};
            var dialogInfo = {
                // id: dialogId,
                width : 1000,
                height : 550,
                closable:true,
                closed:true,
                modal:true,
                shadow:false,
                index:1,
                maximizable:true
            };
            
            if(params){
                params.id = dialogOpts;

            }else if($.type(dialogOpts) === 'string'){
                dialogInfo.id = dialogOpts;
            };

            // 解决自动加载根据嵌入内容展示高度时，弹框不能居中的问题
            dialogInfo.onLoad = function(){
                // 判断页面是否超时
                DefaultPage.reloadPage();

                // 当前获得焦点的元素失去焦点，防止弹框没有回车查询方法时刷新弹框页面内容，产生重复id
                // 判断是否为IE浏览器
                if(navigator.userAgent.toLowerCase().indexOf("msie") > -1){
                    document.getElementsByTagName('body')[0].focus();
                }else{
                    document.activeElement.blur();
                };

                $('#'+dialogOptions.id).dialog('center');
                // 若弹框存在 则onLoad时启用按钮
                if(dialogOptions['buttons']){
                    $(dialogOptions['buttons']).find('.easyui-linkbutton').linkbutton('enable');
                };
            };

            // 弹框打开前解绑前一层级回车事件
            dialogInfo.onBeforeOpen = function(){
                Utils.keyEnter.off(dialogOptions['index']-1); 
            };
            // 弹框关闭后绑定上一级回车事件并销毁当前弹框
            dialogInfo.onClose = function(){
                // 解绑当前层级回车事件，绑定前一层级事件
                Utils.keyEnter.off(dialogOptions['index']); 
                Utils.keyEnter.on(dialogOptions['index']-1); 
                // 销毁弹框 避免多次创建出现重复id
                $('#'+dialogOptions.id).dialog('destroy');
                
                // 清空弹框btn参数
                MenuBarUrl.dialogBtnHtml = '';
            };
            // 若为系统共用弹框 则直接使用默认参数
            if(params){
                dialogOpts = CommonPageScript.commonDialogInfo(params);
            }else if($.type(dialogOpts) === 'string'){
                // 系统共用弹框参数设定
                dialogOpts = CommonPageScript.commonDialogInfo(dialogOpts);
            };
            dialogOptions = $.extend({}, dialogInfo, dialogOpts);
            // 若存在弹框btn
            if(dialogOptions['buttons']){
                // 创建弹框
                $('<div></div>').append(MenuBarUrl.dialogBtnHtml).dialog(dialogOptions);
                // 解析动态创建的弹框buttons
                $.parser.parse(dialogOptions['buttons']);
                //创建时禁用按钮，当onLoad完成后启用
                $(dialogOptions['buttons']).find('.easyui-linkbutton').linkbutton('disable');
            }else{
                // 创建弹框
                $('<div></div>').dialog(dialogOptions);
            };
            
            // 若为修改密码弹框 则为弹框增加样式
            if(dialogInfo.id == 'edit_password'){
                $("#"+dialogOptions.id).addClass('change_password');
            };
            
            this.openDialog(dialogOptions.id);
        };

        // 系统共用弹框参数设定
        CommonPageScript.commonDialogInfo = function (dialogOpts) {

            var dialogInfo = {},dialogOptions = {},dialogId = '';

            if($.type(dialogOpts) !== 'string'){
                dialogId = dialogOpts.id;
            }else{
                dialogId = dialogOpts;
            };
            switch(dialogId){
                case "edit_password" :
                    dialogInfo['title'] = "修改密码";
                    dialogInfo['href'] = MenuBarUrl.editPassword;
                    dialogInfo['width'] = 400;
                    dialogInfo['height'] = 290;
                    break;
                case "addOrder" : 
                    dialogInfo['title'] = "在线订购下单";
                    dialogInfo['href'] = MenuBarUrl.addOrder;
                    dialogInfo['buttons'] = '#addOrderDialogBtn';
                    // 动态创建弹框的buttons
                    MenuBarUrl.dialogBtnHtml = '<div id="'+ dialogInfo['buttons'].slice(1) +'"><center><a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:\'icon-filesavewin8\'" onclick="AddOrderOnline.saveOrder($(this));">保存</a><a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:\'icon-okWin8\'" onclick="AddOrderOnline.confirmOrder($(this));">提交</a></center></div>'
                    dialogInfo['onBeforeClose'] = function(){
                        CommonPageScript.editIndex = undefined;
                    };
                    break;
                case "orderItem" : 
                    dialogInfo['title'] = "成品信息";
                    dialogInfo['href'] = MenuBarUrl.productInfo;
                    //dialogInfo['width'] = 800;
                    dialogInfo['height'] = 550;
                    dialogInfo['index'] = 2;
                    dialogInfo['buttons'] = '#productInfoDialogBtn';
                    // 动态创建弹框的buttons
                    MenuBarUrl.dialogBtnHtml = '<div id="'+ dialogInfo['buttons'].slice(1) +'"><center><a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:\'icon-okWin8\'" onclick="ProductInfo.productConfirm();">确认</a></center></div>'
                    break;
                case "matchingDialog" : 
                    dialogInfo['title'] = "配套";
                    dialogInfo['href'] = MenuBarUrl.matchingInfo;
                    dialogInfo['width'] = 700;
                    dialogInfo['height'] = 550;
                    dialogInfo['index'] = 2;
                    dialogInfo['buttons'] = '#orderItemoneBtn';
                    dialogInfo['onBeforeClose'] = function(){Matching.submitCheck();}
                    // 动态创建弹框的buttons
                    MenuBarUrl.dialogBtnHtml = '<div id="'+ dialogInfo['buttons'].slice(1) +'"><center><a href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:\'icon-okWin8\'" onclick="Matching.confirm();">确认</a></center></div>'
                    break;
                case "viewOrders" : 
                    dialogInfo['title'] = "查看订单";
                    dialogInfo['href'] = MenuBarUrl.viewOrders;
                    break;
                case "viewMonthOrders" : 
                    dialogInfo['title'] = "查看月订单";
                    dialogInfo['href'] = MenuBarUrl.viewMonthOrders;
                    break;
                case "invoiceDialog" : 
                    dialogInfo['title'] = "订单详情页";
                    dialogInfo['href'] = MenuBarUrl.invoiceDetails;
                    break;
                case "deptDialog" : 
                    dialogInfo['title'] = "部门选择";
                    dialogInfo['href'] = MenuBarUrl.queryDept;
                    dialogInfo['width'] = 380;
                    dialogInfo['height'] = 400;
                    break;
                case "chose_dealer" : 
                    dialogInfo['title'] = "经销商信息";
                    dialogInfo['href'] = MenuBarUrl.openChoseDealer;
                    dialogInfo['width'] = 510;
                    dialogInfo['height'] = 515;
                    break;
            };

            if($.type(dialogOpts) !== 'string'){
                dialogInfo = $.extend({}, dialogInfo, dialogOpts);
            };

            return dialogInfo;
        };

        // 弹框页面打开方法
        CommonPageScript.openDialog = function(dialogId){
        	
            $("#"+dialogId).dialog('open');
        };

        // 客户信息及业务配置详情弹框公用
        // infoType: 1  渠道详情  2 PCR车队详情  3 TBR车队详情
        CommonPageScript.openDetails = function(rowId,dealerType,infoType){
            var detailUrl = '',dialogId = '';
            if(infoType == 1){
                dialogId = 'view_channel_detail';
                detailUrl = MenuBarUrl.detailChannel+"?id="+rowId+"&dealerType="+dealerType;
            }else if(infoType == 2){
                dialogId = 'view_fleet_pcr_detail';
                detailUrl = MenuBarUrl.detailPCRFleet+"?busId="+rowId+"&dealerType="+dealerType;
            }else if(infoType == 3){
                dialogId = 'view_fleet_tbr_detail';
                detailUrl = MenuBarUrl.detailTBRFleet+"?busId="+rowId+"&dealerType="+dealerType;
            };
            CommonPageScript.createDialog(dialogId,{href:detailUrl});
        };

        // 经销商查询页面打开及查询方法
        CommonPageScript.openDealerDialog = function(urlType,returnShowId,oneDealerId){
            // CommonPageScript.searchDealerNameValue 回显id名称
            if(returnShowId){
                CommonPageScript.searchDealerNameValue = returnShowId;
            };
            if(oneDealerId !== undefined){
                CommonPageScript.oneDealerId = oneDealerId;
            };
            CommonPageScript.createDialog('chose_dealer');
            MenuBarUrl.choseDealerType = urlType;
        };

        // 弹框页面关闭方法
        CommonPageScript.closeDialog = function(dialogId){
            $("#"+dialogId).dialog('close');
        };



        // 胎别选择提交
        CommonPageScript.factoryTypeSubmit = function($factoryTypeDialog,$factoryTypeCombo){
            // 判断是否需要跳转页面
            var args = $('#backUrl').val();
            var factoryTypeValue = $factoryTypeCombo.combobox('getValue');
            var curUrl = document.location.href;
            var pageType = $('#curPageType').val();
            // 若地址栏为空
            if (curUrl.length == 0) {
                return
            };
            var dealerType = Utils.queryParam('pageType');
            // 使用url传参方式
            if(args == ''){
                // 截取kcgl-web到?之间的字符串
            	var curPath = MenuBarUrl.systemPath;
                var curUrlStart = curUrl.indexOf(curPath);
                var curUrlEnd = curUrl.indexOf('?');
                curUrlEnd = curUrlEnd == -1?curUrl.length:curUrlEnd;
                args = curUrl.substring(curUrlStart+curPath.length,curUrlEnd);
            };
            if(dealerType){
            	pageType = dealerType;
            };
            window.parent.location.href=MenuBarUrl.selectFactoryType+'?factoryType='+factoryTypeValue+'&backUrl='+args+'&pageType='+pageType;            	
        };

        /*  表格初始化以及重新加载数据   *为当opts不存在时的必传参数
        *   allQueryParams 
        *       *gridObj        datagrid表格id 
        *       *isInit         页面全局变量,用于判断 初始化 or 重新加载数据
        *       *url            datagrid 请求地址
        *       queryParams     datagrid 参数
        *       opts            表格属性参数(可包含url,当*url存在时,可不传url)
        *   flag                是否返回整个参数对象
        *   author:  zxy  2016-03-09   
        *   version: 2.0  2016-08-11
        */
        CommonPageScript.dataGridInit = function(allQueryParams,flag){
            var _this = {};
            _this.gridObj = allQueryParams['gridObj'];
            _this.isInit = allQueryParams['isInit'];
            // 用于兼容处理  避免原先已使用此方法的页面报错
            _this.url = allQueryParams['url'];
            _this.queryParams = allQueryParams['queryParams'];
            _this.callback = allQueryParams['callback'];

            // 表格属性参数
            _this.opts = {
                url:_this.url,
                queryParams:_this.queryParams,
                onLoadSuccess:_this.callback,
                pageList:[15,30,50,100],
                pageSize:15
            };

            // 扩展datagrid默认属性及方法
            if(allQueryParams['opts']){
                _this.opts = $.extend(true, {}, _this.opts, allQueryParams['opts']);
            };

            if(!_this.isInit){
                $('#'+_this.gridObj).datagrid(_this.opts);
                _this.isInit = true;
            }else{
                $('#'+_this.gridObj).datagrid('load',_this.queryParams);
            };
            
            return flag?_this:_this.isInit;
        };

        /**
         * 对象获取焦点函数
         */
        CommonPageScript.setFocus = function(obj) {
            if (obj.setSelectionRange) {
                setTimeout(function() {
                    obj.setSelectionRange(0, 0);
                    obj.focus();
                }, 100);
            } else {
                if (obj.createTextRange) {
                    var range = obj.createTextRange();
                    range.collapse(true);
                    range.moveEnd("character", 0);
                    range.moveStart("character", 0);
                    range.select();
                }
                try {
                    obj.focus();
                } catch (e) {
                }
            }
        };

        // 退出登录
        CommonPageScript.loginOut = function(){
            window.parent.location.href=MenuBarUrl.loginOut;
        };

        // 当表格成功加载时执行    
        CommonPageScript.onLoadSuccess = function(datagrId,row){     
            var rowData = row.rows, grid = $(datagrId);
            $.each(rowData,function(idx,val){//遍历JSON
                if(val.checked==true || val.selected==true){
                    // 如果数据行为已选中则选中改行
                    grid.datagrid("checkRow", idx);
                }
            });              
        }; 		 
		  
        /*  扩展省市县地址下拉联动及赋值
        *   address 
        *       province      省下拉框jQ对象
        *       city          市下拉框jQ对象
        *       country       县下拉框jQ对象
        *       url           各省市县请求地址,默认使用leftmenu.jsp请求地址
        *   addressValues     存在该参数时用于赋值,同样存在province,city,country三个属性
        *   author: zxy   20160311
        */
        CommonPageScript.choseAddressCombobox = function(address,addressValues){
            var realAddress = {
                province:address.province,
                city:address.city,
                country:address.country,
                provinceUrl:MenuBarUrl.queryProvince,
                // 参数 provinceCode
                cityUrl:MenuBarUrl.queryCity,
                // 参数 cityCode
                countryUrl:MenuBarUrl.queryArea,
                // 判断是否为编辑时的默认赋值
                isFirstSetValue:true
            };
            var provinceData = [],cityData = [],countryData = [];

            var provinceId = realAddress['province'].combobox({
                url:realAddress.provinceUrl,
                onLoadSuccess:function(){ 
                    provinceData = realAddress['province'].combobox('getData');
                    if(realAddress.isFirstSetValue && addressValues && addressValues['province']){
                        realAddress['province'].combobox('select',addressValues['province']);
                        realAddress['city'].combobox('select',addressValues['city']);
                        realAddress['country'].combobox('select',addressValues['country']);
                    }
					//xujb 库存省市县查询条件
				    if(typeof InventoryQuery =="object"){
						
					   address.province.combobox('keyEnter',InventoryQuery.queryList);
					   address.city.combobox('keyEnter',InventoryQuery.queryList);
				       address.country.combobox('keyEnter',InventoryQuery.queryList);
	
					}
                },
			
                onChange:function(newValue, oldValue){
                    // 重置 市下拉选项内容
                    if(newValue != "" && newValue != undefined){
						/*
						 * 修改了combobox getValue 为getText
						 * xujb 2016-05-09
						 */
                        var provinceCode = realAddress['province'].combobox('getText');
                        var city = realAddress['city'].combobox({
                            url:realAddress.cityUrl,
                            onBeforeLoad:function(param){
                            	param.provinceCode=provinceCode;
                            },
                            onLoadSuccess:function(){
                                cityData = realAddress['city'].combobox('getData');
								
									
				  					if(typeof InventoryQuery =="object"){
						
					   					address.city.combobox('keyEnter',InventoryQuery.queryList);
				       					
									}
                            },
                            onChange:function(newValue, oldValue){
								/*
						 		 * 修改了combobox getValue 为getText
						 		 * xujb 2016-05-09
								*/
                                var cityCode = realAddress['city'].combobox('getText');
                                if(newValue != ""  && newValue != undefined){
                                    // 重置 县下拉选项内容
                                    realAddress['country'].combobox({
                                        url:realAddress.countryUrl,
                                        onBeforeLoad:function(param){
                                        	param.cityCode=cityCode;
                                        },
                                        onLoadSuccess:function(){
                                            countryData = realAddress['country'].combobox('getData');
												
				    						if(typeof InventoryQuery =="object"){
						
				      							 address.country.combobox('keyEnter',InventoryQuery.queryList);
	
											}
                                        }
                                    });
                                }else{
                                    realAddress['country'].combobox('clear').combobox('loadData',[]);
                                }
                                realAddress['country'].combobox('loadData',countryData);
                            }
                        });
                    }else{
                        realAddress['city'].combobox('clear').combobox('loadData',[]);
                        realAddress['country'].combobox('clear').combobox('loadData',[]);
                    }
                    realAddress['city'].combobox('loadData',cityData);
                    realAddress['country'].combobox('clear').combobox('loadData',[]);
                }

            });
            if(provinceData.length != 0){
                realAddress['province'].combobox('loadData',provinceData);
            }
        };

        /*
         * 调用方式:级别下拉框onSelect:function(record){CommonPageScript.onSelectDealerType(record,'dealName')}
         * 一级经销商查看渠道出入库退货明细,根据所选的经销商级别动态隐藏和显示经销商选择
         * params 参数  record 下拉选的对象 dealerId 经销商选择框id
         * author: wyf   20160316
         */
        CommonPageScript.onSelectDealerType = function(record,dealerId) {
            this._dealerId = $("#"+dealerId); 
            // ==1:一级经销商级别，隐藏经销商的选择框 ==2:显示经销商选择框
            if(record.value == 1){
                this._dealerId.textbox('clear').next().hide();
            }else if(record.value == 2){
                this._dealerId.next().show();
            };
        };

        /*  设置center页面权限按钮
        *   toolbarObj  权限按钮父级对象
        *   author: zxy 2016-07-19
        */
        CommonPageScript.setAuthority = function($toolbarObj,showBtn){
            var authorityAttr = '';
            //var authorityAttr = $('#leftMenu a[center-hash="'+ MenuBar.centerOpts.hashContent +'"]').attr('center-menu');
            $toolbarObj.attr('show',false);
            if(showBtn){
                authorityAttr = showBtn;
            };
            if(authorityAttr){
                var authorityArr = authorityAttr.split(',');
                for(var i = 0;i < authorityArr.length; i++){
                    if(authorityArr[i] !== ''){
                        $toolbarObj.eq(authorityArr[i]).attr('show',true);
                    }
                };
            }
            $toolbarObj.filter("[show]").filter("[show!=true]").hide();
        };

        /*  
        *   开启表格编辑
        */
        CommonPageScript.editIndex = undefined;
        CommonPageScript.endEditing = function(gridId){
            var $grid;
            if($.type(gridId) === 'string'){
                $grid = $('#'+gridId);
            }else{
                $grid = gridId;
            };

            if(CommonPageScript.editIndex == undefined){return true;};
            if($grid.datagrid('validateRow', CommonPageScript.editIndex)){
                $grid.datagrid('endEdit', CommonPageScript.editIndex);
                CommonPageScript.editIndex = undefined;
                return true;
            }else{
                return false;
            };
        };

        CommonPageScript.onClickRow = function(index, row,gridId){
            var $grid;
            if($.type(gridId) === 'string'){
                $grid = $('#'+gridId);
            }else{
                $grid = gridId;
            };
            if(CommonPageScript.editIndex != index){
                if(CommonPageScript.endEditing(gridId)){
                    $grid.datagrid('selectRow', index).datagrid('beginEdit', index);
                    CommonPageScript.editIndex = index;
                }else{
                    $grid.datagrid('selectRow', CommonPageScript.editIndex);
                };
            };
        };

        /*  结束一行编辑状态后 自动计算
        *   calOpts: {
                gridId:'fillMonthOrderGrid',    // 表格id
                totalField:'qtyAccept',         // 相加合计字段
                calFields:['qtyFirstaccept','qtySecaccept','qtyThreeaccept'],  // 相加字段
                reduceField:{                   // 需要相减的字段对象
                    all:'qty',                  // 被减数字段
                    reduceNums:'qtyAccept',     // 减数字段
                    resoult:'lostNums'          // 差字段
                    isOverZero:true             // 是否需要大于0
                }
            }
        *   author: zxy 2016-08-08
        */
        CommonPageScript.calculateRow = function(index, row, changes, calOpts,isShowZero){
            var curRows = $('#' + calOpts.gridId).datagrid('getData');
            var totalNum = 0, temporaryFieldVal = $.extend(true, {}, row);
            //判断是否进行加法运算
            if(calOpts.calFields) {
                for (var i = 0; i < calOpts.calFields.length; i++) {
                    if (!temporaryFieldVal[calOpts.calFields[i]]||temporaryFieldVal[calOpts.calFields[i]] === '') {
                        temporaryFieldVal[calOpts.calFields[i]] = 0;
                    };
                    totalNum += parseInt(temporaryFieldVal[calOpts.calFields[i]]);
                };

                // 总计字段为空时，自动根据计算字段累加；若不为空，则清空计算字段
                // if(row[calOpts.totalField] === ''){  // 总计字段现控制为不可编辑
                if (isNaN(totalNum)) {
                    row[calOpts.totalField] = '';
                } else {
                    //totalNum是否展示0
                    if(isShowZero == null){
                        isShowZero = false;
                    }
                    if (totalNum === 0 && isShowZero===false) {
                        row[calOpts.totalField] = '';
                    } else {
                        row[calOpts.totalField] = totalNum;
                    };
                };
                // }else{
                //     if(totalNum !== parseInt(row[calOpts.totalField])){
                //         for(var j = 0; j < calOpts.calFields.length; j++){
                //             row[calOpts.calFields[j]] = '';
                //         };
                //     };
                // };
            };

            // 若存在减法字段
            if(calOpts.reduceField){
                var reduceNums = row[calOpts.reduceField.reduceNums];
                // 避免未进行输入操作时页面显示0
                if(row[calOpts.reduceField.reduceNums]){
                    //row[calOpts.reduceField.reduceNums] = 0;
                    //reduceNums = 0;  // 避免未进行输入操作时页面显示0
                //}else{
                    var reduceResoult =parseInt(row[calOpts.reduceField.all]) - parseInt(reduceNums);

                    // 判断减法结果是否需在小于0时显示为0
                    if(reduceResoult < 0 && calOpts.reduceField.isOverZero){
                        reduceResoult = 0;
                    };
                    row[calOpts.reduceField.resoult] = reduceResoult;
                };
            };

            // 若存在footer 则根据所传参数计算相应列的footer结果
            var footerObjs = {};
            if(calOpts.footer){
                var footerLen = calOpts.footer.length;
                for(var rowStep = 0; rowStep < curRows.rows.length; rowStep++){
                    for(prop in calOpts.footer){
                        if(!footerObjs[prop]){
                            footerObjs[prop] = 0;
                        };
                        if(!curRows.rows[rowStep][prop]){
                            footerObjs[prop] += 0;
                        }else{
                            footerObjs[prop] += parseInt(curRows.rows[rowStep][prop]);
                        };
                    };
                };
            };

            $('#' + calOpts.gridId).datagrid('refreshRow',index);
            if(calOpts.footer){
                return [footerObjs];
            };
        };

        /*  表格行数据操作  未选择任何行时进行提示
        *   $grid       表格对象
        *   callback    选中后的回调函数
        *   isMulti     是否支持多选,若为多选，则选中多行时不提示;若为单选，则选中多行数据时将弹出提示
        *   author: zxy 2016-08-08
        */
        CommonPageScript.operateRowData = function($grid,callback,isMulti){
            var selectRow = $grid.datagrid('getSelections');
            if((selectRow.length === 1 && !isMulti) || (selectRow.length >= 1 && isMulti)){
                callback();
            }else{
                if((selectRow.length === 1 && isMulti) || selectRow.length >= 1 && isMulti === undefined){
                    callback();
                }else{
                    Utils.keyEnterMessager();
                };
            };

            return selectRow;
        };

        /*  表格非空字段校验
        *   $grid       表格对象
        *   fields      需要校验的字段
        *   author: zxy 2016-08-16
        */
        CommonPageScript.gridNoNullCheck = function($grid,fields){
            var gridDatas = $grid.datagrid('getData');
            var gridDatasLen = gridDatas.rows.length;
            var fieldsLen = fields.length;
            var returnDatas = gridDatas.rows;
            if(gridDatasLen){
                for(var i = 0; i < gridDatasLen; i++){
                    var isValidate = true;
                    if(!isValidate){ 
                        returnDatas = false;
                        return false;
                    };
                    
                    for(var fieldStep = 0; fieldStep < fieldsLen; fieldStep++){
                        var fieldVal = gridDatas.rows[i][fields[fieldStep]['fieldval']];
                        if(returnDatas && (fieldVal === '' || fieldVal === null)){
                            Utils.keyEnterMessager({
                                msg:'请填写第' + (i+1) + '行' + fields[fieldStep]['fieldName'] + '！',
                                onClose:function(){
                                    CommonPageScript.onClickRow( i, null, $grid);
                                }
                            });
                            isValidate = returnDatas = false;
                            return false;
                        };
                    };
                };
            }else{
                // 若表格数据为空
                returnDatas = 'empty';
            };

            return returnDatas;
        };

        /*  easyui datagrid中的combobox结束编辑时显示value值的bug校正
        *   $grid           表格对象
        *   fields          需要校正的字段
        *       fieldText   显示的中文
        *       fieldVal    显示的value
        *   author: zxy 2016-08-16
        */
        CommonPageScript.showGridComboText = function($grid,index,fields){
            var fieldsLen = fields.length;
            for(var i = 0; i < fieldsLen; i++){
                var ed = $grid.datagrid('getEditor',{index:index,field:fields[i]['fieldText']});
                var fieldText = $(ed.target).combobox('getText');
                var fieldId = $grid.datagrid('getRows')[index][fields[i]['fieldText']];
                $grid.datagrid('getRows')[index][fields[i]['fieldText']] = fieldText;
                $grid.datagrid('getRows')[index][fields[i]['fieldVal']] = fieldId;
            };
        };

        /*  easyui datagrid中的combobox开启编辑时显示value值的bug校正默认选中回显值
        *   $grid           表格对象
        *   fields          需要校正回显的字段
        *       fieldText   显示的中文
        *       fieldVal    显示的value
        *   author: zxy 2016-08-23
        */
        CommonPageScript.setGridComboText = function($grid,index,row,fields){
            var fieldsLen = fields.length;
            for(var i = 0; i < fieldsLen; i++){
                var ed = $grid.datagrid('getEditor',{index:index,field:fields[i]['fieldText']});
                $(ed.target).combobox('select',row[fields[i]['fieldVal']]);
            };

            return true;
        };

        /*  easyui datagrid表格编辑行中的下拉框多级联动
        *   comboParams             表格参数对象
        *       url                 请求地址
        *       data                请求参数
        *       getDataParams       根据字段获取请求参数(可不传，不传时使用data作为请求参数;否则使用getDataParams扩展data作为参数)
        *       $grid               表格对象
        *       curField            当前选中的字段名
        *       reloadField         下级联动字段名
        *       otherField          其余联动需置空的字段名,数组格式
        *   author: zxy 2016-08-17
        */
        CommonPageScript.gridComboFollowChange = function(comboParams){
            // 获取当前操作行
            var curRowEd = comboParams['gridObj'].datagrid('getEditors',CommonPageScript.editIndex);
            // 存储需要联动的下拉对象
            var $curEd,$reloadEd,$resetEd = [];

            // 请求参数拼接
            var dataParams = {};          

            for(var i = 0; i < curRowEd.length; i++){
                if(curRowEd[i].field === comboParams.curField){
                    $curEd = $(curRowEd[i].target);
                };
                if(curRowEd[i].field === comboParams.reloadField){
                    $reloadEd = $(curRowEd[i].target);
                };
                if(comboParams.otherField){
                    for(var saveStep = 0; saveStep < comboParams.otherField.length; saveStep++){
                        if(curRowEd[i].field === comboParams.otherField[saveStep]){
                            $resetEd[saveStep] = $(curRowEd[i].target);
                        };
                    };
                };
                
                // 当拼接请求参数存在时,获取相应传参字段值后extend原先的data参数
                if(comboParams.getDataParams){
                    for(vParam in comboParams.getDataParams){
                        if(curRowEd[i].field === comboParams.getDataParams[vParam]) {
                            var tarVal = $(curRowEd[i].target).combobox('getValue');
                            var tarText = $(curRowEd[i].target).combobox('getText');
                            var rowInfo = comboParams['gridObj'].datagrid('getSelected');
                            if(tarVal === rowInfo[vParam]){
                                if(!rowInfo[vParam]){
                                    dataParams[vParam] = tarVal;
                                }else{
                                    dataParams[vParam] = rowInfo[vParam];
                                };
                            }else{
                                dataParams[vParam] = tarVal;
                            };
                        };
                    };
                };
            };

            // 合并请求参数
            dataParams = $.extend({},dataParams, comboParams.data);

            var queryOpts = {
                url: comboParams.url,
                type:'POST',
                data:dataParams,
                callback:function(data){
                    // 遍历需要重置的下拉框字段 将选项置空
                    if(comboParams.otherField){
                        for(var resetStep = 0; resetStep < comboParams.otherField.length; resetStep++){
                            $resetEd[resetStep].combobox('clear').combobox('loadData',[]);
                        };
                    };
                    // 判断需要联动的下拉框是否存在
                    if(comboParams.reloadField){
                        // 对下级联动下拉选项的字段重载选项
                        $reloadEd.combobox('loadData',data.data);
                    };

                }
            };
            
            Utils.doAjax(queryOpts);
        };

        /*  表格列formatter 增加鼠标悬停title 用于当列数据太多无法显示完整时
        *   author: zxy 2016-08-12
        */
        CommonPageScript.formatterColContent = function(value,row,index){
            if(value === null){
                value = '';
            };
            return "<span title=\""+value+"\">"+value+"</span>";
        };

        /*  form表单赋值
        *   data                值对象
        *   $form               表单对象
        *   author: zxy 2016-08-18
        */
        CommonPageScript.loadEditForm = function(data, $form){
            // 寻找存在name属性的input批量赋值
            $form.find('input,textarea').filter('[name]').each(function(index,ele){
                var $ele = $(ele);
                var nameVal = $ele.attr('name');
                $ele.val(data[nameVal]);
            });
        };

        /*  表格输入长度校验
         *   $grid             校验表格对象
         *   msg               校验失败的提示语
         *   callback          校验成功后的回调函数
         *   author: zxy 2016-09-02
         */
        CommonPageScript.checkGridValidate = function($grid,msg,callback){
            if($grid.datagrid('validateRow', CommonPageScript.editIndex) || (!CommonPageScript.editIndex && CommonPageScript.editIndex !== 0)){
                callback();
            }else{
                Utils.keyEnterMessager({
                    msg:msg
                });
            };
        };
        
        /*   删除一行记录
         *   参数：url  请求路径
         *       gridSelector  datagrid的ID
         *   author: yyp
         */
        CommonPageScript.deletes = function (url,gridSelector,opts){
        	var row = $('#'+gridSelector).datagrid('getSelected');
        	if (row) {
                var deleteData = row.id;
                $.messager.confirm("删除确认","您确认想要删除记录吗?",function(r){
                    if(r){
                        var defalutOpts = {
                            method: 'post',
                            url: url + deleteData,
                            data: {
                                id: deleteData
                            },
                            messager: function (data) {
                                if (data) {
                                    $.messager.alert('提示信息', '删除成功！', 'info');
                                    $('#'+gridSelector).datagrid('load');
                                }
                            },
                            callback: function(data) {
                            	$('#'+gridSelector).datagrid('reload');
                            },
                            skip: true
                        };
                        var options = $.extend({},defalutOpts, opts);

                        Utils.doAjax(options);
                    }
                });
            } else {
                $.messager.alert('提示信息', '请选择一行记录！', 'info');
            }
        };


        /*   汇总和明细模式切换数据刷新
         *   参数：$comboSelect：明细和汇总切换的combox
         *       $searchDetail：查询条件1
         *       $searchTotal：查询条件2
         *   author: ly
         *
         */
        CommonPageScript.selectFreshData = function ($comboSelect, $searchDetail, $searchTotal) {
            var selectOption = $comboSelect.combobox('getValue');
            if (selectOption == "total") {//汇总
                CommonPageScript.dataReverse($searchDetail, $searchTotal, "total");
            } else if (selectOption == "details") {//明细
                CommonPageScript.dataReverse($searchTotal, $searchDetail, "detail");
            }
        };
        //汇总和明细模式切换时页面的变化
        CommonPageScript.dataReverse = function ($searchOne, $searchTwo, type) {

            var $obj = $searchTwo.find('input').filter('[id]:not(".date")');//要赋值的查询控件
            $searchOne.find('input').filter('[id]').each(function (index, ele) {
                var $ele = $(ele);
                var value = $ele.combobox("getValue");
                $obj.eq(index).combobox("setValue", value);
            });
            if (type == "detail") {
                //初始化时间
                var date = Utils.dateFormat(new Date(), "yyyy-MM").toString();
                $searchTwo.find(".date").datebox({value: date});
            } else if (type == "total") {

                //初始化时间
                var queryStartTime = $searchTwo.find(".date").eq(0);
                var queryEndTime = $searchTwo.find(".date").eq(1);

                var date = Utils.dateFormat(new Date(), "yyyy-MM").toString();
                queryEndTime.datebox({value: date});
                var date1 = Utils.dateFormat(new Date(), "yyyy").toString();
                queryStartTime.datebox({value: date1 + "-01"});

                //月份开始时间小于结束时间
                Utils.DateboxMonthCompare(queryStartTime, queryEndTime);
            }
            $searchOne.removeClass('displayBlock').addClass('displayNone');
            $searchTwo.removeClass('displayNone').addClass('displayBlock');
        };

        /*   上传文件实例化公用
         *   默认不可多选，并且一次只能选择一个文件上传
         *   参数：selector：初始化对象
         *   author: jh
         */
        CommonPageScript.uploadify = function(selector,opts){

            var defalutOpts = {
                'swf': 'resources/js/uploadify/uploadify.swf',
                'buttonCalss': 'btnclass',
                'cancelImg': 'resources/js/uploadify/uploadify-cancel.png',
                //'buttonImage' :'resources/js/uploadify/images/browse-btn.png',
                'width': '120',
                'queueId': "fileQueue",
                'fileObjName': 'fileData',
                'fileTypeExts': '*.xls;*.xlsx',
                'fileTypeDesc': '请上传格式为 doc / docx / pdf / xls / xlsx 的文件',
                'auto': false,
                'multi': false,//是否允许多文件上传
                'queueSizeLimit': 10, //如果选择的文件数量超出此限制将会出发onSelectError
                'uploadLimit': 10,
                'successTimeout': 1800,   //上传超时时间,默认是30s
                'fileSizeLimit': '25MB',
                //'buttonText': "选择文件",
                'button_image_url': 'resources/js/uploadify/browse-btn.png',//解决BUG：打开页面报404错误
                'removeCompleted': true,
                'method': "POST",
                'onSelectError': function (file, errorCode, errorMsg) {
                    var msgText = "上传失败\n";
                    switch (errorCode) {
                        case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:

                            msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                            break;
                        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                            msgText += "文件大小超过限制( " + this.settings.fileSizeLimit + " )";
                            break;
                        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                            msgText += "文件大小为0";
                            break;
                        case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                            msgText += "文件格式不正确\n" + this.settings.fileTypeDesc;
                            break;
                        default:
                            msgText += "错误代码：" + errorCode + "\n" + errorMsg;
                    }
                    // alert(msgText);
                    $.messager.alert("提示信息", msgText, "error");
                },//方法被重写
                'onUploadError': function (file, errorCode, errorMsg, errorString) {
                    // 手工取消不弹出提示
                    if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED
                        || errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
                        return;
                    }
                    var msgText = "上传失败\n";
                    switch (errorCode) {
                        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                            if (errorMsg == '302') {
                                window.location = "<c:url value=" / " />";
                            }
                            msgText += "HTTP 错误\n" + errorMsg;
                            break;
                        case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
                            msgText += "上传文件丢失，请重新上传";
                            break;
                        case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                            msgText += "IO错误";
                            break;
                        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                            msgText += "安全性错误\n" + errorMsg;
                            break;
                        case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                            msgText += "每次最多上传 " + this.settings.uploadLimit + "个";
                            break;
                        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                            msgText += errorMsg;
                            break;
                        case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
                            msgText += "找不到指定文件，请重新操作";
                            break;
                        case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                            msgText += "参数错误";
                            break;
                        default:
                            msgText += "文件:" + file.name + "\n错误码:" + errorCode + "\n"
                                + errorMsg + "\n" + errorString;
                    }
                    // alert(msgText);
                    $.messager.alert("提示信息", msgText, "error");
                },//方法被重写
                'onCancel': function (file) {
                    $('#' + file.id).remove();
                },
                onFallback: function () { //Flash无法加载错误
                    $.messager.alert("提示信息", "您未安装FLASH控件，无法上传！请安装FLASH控件后再试。", "error");

                },
                onSWFReady: function () {
                    // 用于解决IE下 点击上传按钮后 浏览器页签标题改变的问题
                    document.title = "正新订单管理系统";
                },
                onDialogOpen: function () {
                    // 用于解决IE下 点击选择文件按钮后 浏览器页签标题改变的问题
                    document.title = "正新订单管理系统";
                }
            };

            var options = $.extend({}, defalutOpts, opts);

            // 初始化
            $(selector).uploadify(options);

            $(selector).find('Object').each(function () {
                $(this).css('position', '');//解决BUG：浏览按钮有一半不能点击
            });
        };


        /*   用于单页面切换菜单时清除页面中独立创建的window对象
         *   _pageGlobalParam       用于存放待清空的对象
         *   add(string格式)        在创建的其他独立window对象时，将对象名使用add方法存放到待清空的对象_中
         *   clear                  清除单页面中创建的独立window对象
         *   author: zsk 2016-09-08
         */
        CommonPageScript.globalVariable = {
            _pageGlobalParam : {

            },

            add : function(varName){
                this._pageGlobalParam[varName] = true;
            },

            clear : function(){
                for(var item in this._pageGlobalParam){
                    if(window[item]){
                        window[item] = undefined;
                    };
                    delete this._pageGlobalParam[item];
                };
            }
        };

        /*   用于初始化并加载经销商、下单公司、组别、客户代号下拉选项
         *   dataObj                初始化对象参数
         *      $obj                    初始化对象
         *      param                   combobox初始化参数
         *   author: zxy 2016-09-13
         */
        CommonPageScript.getCommonDatas = function (dataObj) {
            //参数:groups,dealers,facs,codes,roles
            var dataArr,defaultItem = '',$dealerCombo;
            var dataDefaultParam = {
                panelHeight:'150',
                editable:false,
                width:170,
                valueField:'id'
            };

            for(var i in dataObj){
                dataDefaultParam.panelWidth = null;
                var commonComboParams = {};
                if(i === 'dealers'){
                    $dealerCombo = dataObj[i]['$obj'];
                    if(!dataObj[i]['disSearch'] && MenuBar.basicUserInfo.isInner){
                        dataObj[i]['param'].editable = true;
                        dataObj[i]['param'].filter = function(q, row){
                            var opts = $(this).combobox('options');
                            return row[opts.textField].indexOf(q) >= 0;
                        };
                        dataObj[i]['param'].onHidePanel = function(){
                            var comVal = $dealerCombo.combobox('getValue');
                            var comTex = $dealerCombo.combobox('getText');
                            if(comVal === comTex || comTex ===''){
                                $dealerCombo.combobox('setText','全部').combobox('setValue','');
                            };
                        };
                    };
                    dataDefaultParam.panelWidth = 220;
                };
                //无数据的条件
                if(!(MenuBar.basicUserInfo===undefined || MenuBar.basicUserInfo[i]===undefined||MenuBar.basicUserInfo[i].length <= 0)){
                    commonComboParams = $.extend(true, {}, dataDefaultParam, dataObj[i]['param']);
                    //下单公司的value取值是shortCode
                    var valueFiled=dataObj[i]['param'].valueFiled;
                    if(valueFiled){
                        commonComboParams.valueField="shortCode";
                        defaultItem = MenuBar.basicUserInfo[i][0][valueFiled];
                    }else{
                        defaultItem = MenuBar.basicUserInfo[i][0].id;
                    };
                    // 判断是否只显示海燕厂
                    if(dataObj[i]['onlyHP']){
                        commonComboParams.readonly = true;
                        for(var j = 0;j < MenuBar.basicUserInfo[i].length;j++){
                            if(MenuBar.basicUserInfo[i][j].shortCode === 'HP'){
                                defaultItem = MenuBar.basicUserInfo[i][j].id;
                            };
                        };
                    };

                    // 判断是否显示 全部 选项
                    if(!dataObj[i]['hideAll'] && !dataObj[i]['onlyHP'] && MenuBar.basicUserInfo.isInner){
                        var addAllDatas = MenuBar.basicUserInfo[i].slice(0);
                        if(valueFiled){
                            //下单公司的value取值是shortCode
                            addAllDatas.splice(0,0,{displayName:'全部',groupName:'全部',shortName:'全部',shortCode:''});
                        }else{
                            addAllDatas.splice(0,0,{displayName:'全部',groupName:'全部',shortName:'全部',id:''});
                        }
                        commonComboParams.data = addAllDatas;
                        defaultItem = '';
                    }else{
                        commonComboParams.data = MenuBar.basicUserInfo[i];
                    };
                };
                dataObj[i]['$obj'].combobox(commonComboParams).combobox('select',defaultItem);
            };
        };

        /**
         * 把row指定字段中的字符串"" 格式化为 null
         * @param $grid
         * @param row
         * @param fields
         * @returns {boolean}
         */
        CommonPageScript.formatEmptyToNull = function(row,fieldOpts){
            var fields=fieldOpts.formatFields;
            var fieldsLen = fields.length;
            for(var i = 0; i < fieldsLen; i++){
                row[fields[i]] = (row[fields[i]]===''?null:row[fields[i]]);
            };
            return true;
        }

    })(jQuery,window);